package org.leyi.shop.common.annotation;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.leyi.shop.common.exception.BusinessException;
import org.leyi.shop.common.response.EnumResponse;
import org.leyi.shop.model.vo.SafetyUser;
import org.leyi.shop.util.HttpServletUtils;
import org.springframework.stereotype.Component;

import static org.leyi.shop.common.Constant.*;

/**
 *
 * description:  注解的动态代理
 * @author  lenovo
 * create 2024/5/6-22:07 */
@Aspect
@Slf4j
@Component
public class AnnotationHandler {
    @Around("@annotation(org.leyi.shop.common.annotation.IsAdmin)")
    public Object IsAdmin(ProceedingJoinPoint pj)
    {
        HttpServletRequest request = HttpServletUtils.getHttpServletRequest();
        if(request.getSession()==null)
        {
            throw new BusinessException(EnumResponse.USER_NOT_LOGIN);
        }
        SafetyUser safetyUser = (SafetyUser) request.getSession().getAttribute(REQUEST_SESSION_USER_KEY);
        if(safetyUser==null){
            throw new BusinessException(EnumResponse.USER_NOT_LOGIN);
        }
        if(safetyUser.getRole()<ADMIN_ROLE)
        {
            throw new BusinessException(EnumResponse.AUTHORITY_ERR);
        }
        try {
           return pj.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
    @Around("@annotation(org.leyi.shop.common.annotation.IsSuperAdmin)")
    public Object IsSuperAdmin(ProceedingJoinPoint pj)
    {
        HttpServletRequest request = HttpServletUtils.getHttpServletRequest();
        if(request.getSession()==null)
        {
            throw new BusinessException(EnumResponse.USER_NOT_LOGIN);
        }
        SafetyUser safetyUser = (SafetyUser) request.getSession().getAttribute(REQUEST_SESSION_USER_KEY);
        if(safetyUser==null){
            throw new BusinessException(EnumResponse.USER_NOT_LOGIN);
        }
        if(safetyUser.getRole()<SUPER_ADMIN_ROLE)
        {
            throw new BusinessException(EnumResponse.AUTHORITY_ERR);
        }
        try {
            return pj.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
    @Around("@annotation(org.leyi.shop.common.annotation.IsLogin)")
    public Object IsLogin(ProceedingJoinPoint pj)
    {
        HttpServletRequest request = HttpServletUtils.getHttpServletRequest();
        if(request.getSession()==null||request.getSession().getAttribute(REQUEST_SESSION_USER_KEY)==null)
        {
            throw new BusinessException(EnumResponse.USER_NOT_LOGIN);
        }
        try {
            return pj.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}
